import type { App, DirectiveBinding } from "vue";
import { useUserStore } from "@/store/user";

/**
 * 核心判断函数
 */
function checkPermission(required: string | string[]): boolean {
    const { roleCode, powers } = useUserStore();

    if (Array.isArray(required)) {
        return (
            required.includes(roleCode) ||
            required.some((code) => powers.includes(code))
        );
    } else {
        return roleCode === required || powers.includes(required);
    }
}

/**
 * 自定义指令 v-permission
 * 用法：v-permission="'user:add'" 或 v-permission="['user:add','admin']"
 */
function permissionDirective(el: HTMLElement, binding: DirectiveBinding) {
    const required = binding.value;
    if (!checkPermission(required)) {
        el.parentNode && el.parentNode.removeChild(el);
    }
}

/**
 * 在 main.ts 中调用
 */
export function setupPermission(app: App) {
    app.directive("permission", {
        mounted(el, binding) {
            permissionDirective(el, binding);
        },
        updated(el, binding) {
            // 避免更新时权限变化没反应
            permissionDirective(el, binding);
        },
    });

    // 全局方法：hasPermission
    app.config.globalProperties.$hasPermission = checkPermission;
}

export { checkPermission as hasPermission };
